#include <stdio.h>
#include <stdlib.h>
#include <string.h>

extern "C" {
#include <libavutil/frame.h>
#include <libavutil/mem.h>
#include <libavcodec/avcodec.h>
#include <libavformat/avformat.h>
#include "libswresample/swresample.h"
#include "libswscale/swscale.h"
}

//#pragma comment(lib,"../../ffmpeg-20180508-293a6e8-win32-dev/lib/avcodec.lib")
//#pragma comment(lib,"../../ffmpeg-20180508-293a6e8-win32-dev/lib/avformat.lib")
//#pragma comment(lib,"../../ffmpeg-20180508-293a6e8-win32-dev/lib/avfilter.lib")
//#pragma comment(lib,"../../ffmpeg-20180508-293a6e8-win32-dev/lib/avutil.lib")

//#if _MSC_VER
//#define snprintf _snprintf_s
//#define PRIx64       "I64x"
//#define PRIX64       "I64X"
//#endif

#define AUDIO_INBUF_SIZE 20480
#define AUDIO_REFILL_THRESH 4096

static bool isFirstPkg = true;
static void printfFormat(AVCodecContext* pCodecCtx)
{
    if(isFirstPkg)
    {
        printf("===================\n");
        //printf("channel_layout : %d\n", pCodecCtx->channel_layout);
        printf("channel_num : %d\n", av_get_channel_layout_nb_channels(pCodecCtx->channel_layout));
        printf("sample_fmt : %s\n", av_get_sample_fmt_name(pCodecCtx->sample_fmt));
        printf("bytes_per_sample : %d\n", av_get_bytes_per_sample(pCodecCtx->sample_fmt));
        printf("sample_rate : %d\n", pCodecCtx->sample_rate);
        printf("===================\n");
        isFirstPkg = false;
    }
    //if(pCodecCtx->channel_layout!=0) exit(0);
}

static FILE* outdec = NULL;
static SwrContext *swr_ctx = NULL;
static uint64_t out_ch_layout = av_get_default_channel_layout(1);
static enum AVSampleFormat out_format = AV_SAMPLE_FMT_S16;
static int out_sample_rate = 16000;
uint8_t *out_buffer = (uint8_t *) av_malloc(44100 * 2);
static void decode(AVCodecContext *dec_ctx, AVPacket *pkt, AVFrame *frame, FILE *outfile)
{
    int i, ch;
    int ret, data_size;


    /* 发送编码数据包给解码器 */
    ret = avcodec_send_packet(dec_ctx, pkt);
    //if (ret < 0) {
    if (ret < 0 && ret != AVERROR(EAGAIN) && ret != AVERROR_EOF){
        fprintf(stderr, "Error submitting the packet to the decoder\n");
        return;
    }

    printfFormat(dec_ctx);

    /* 读取所有的输出帧*/
    //while (ret >= 0) {
        ret = avcodec_receive_frame(dec_ctx, frame);
        if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF)
            return;
        else if (ret < 0) {
            fprintf(stderr, "Error during decoding\n");
            exit(1);
        }
        data_size = av_get_bytes_per_sample(dec_ctx->sample_fmt);
        if (data_size < 0) {
            /* 不应该出现的情况 */
            fprintf(stderr, "Failed to calculate data size\n");
            exit(1);
        }
        for (i = 0; i < frame->nb_samples; i++)
            for (ch = 0; ch < dec_ctx->channels; ch++)
                fwrite(frame->data[ch] + data_size*i, 1, data_size, outfile);
    //}

    // 设置通道数或channel_layout
        if (frame->channels > 0 && frame->channel_layout == 0)
            frame->channel_layout = av_get_default_channel_layout(frame->channels);
        else if (frame->channels == 0 && frame->channel_layout > 0)
            frame->channels = av_get_channel_layout_nb_channels(frame->channel_layout);

        printf("channel_num : %d\n", av_get_channel_layout_nb_channels(frame->channel_layout));
        printf("sample_fmt : %s\n", av_get_sample_fmt_name((AVSampleFormat)frame->format));
        printf("bytes_per_sample : %d\n", av_get_bytes_per_sample((AVSampleFormat)frame->format));
        printf("sample_rate : %d\n", frame->sample_rate);
        printf("out channel_num : %d\n", av_get_channel_layout_nb_channels(out_ch_layout));
        printf("out sample_fmt : %s\n", av_get_sample_fmt_name((AVSampleFormat)out_format));
        printf("out bytes_per_sample : %d\n", av_get_bytes_per_sample((AVSampleFormat)out_format));
        printf("out sample_rate : %d\n", out_sample_rate);
        // 设置转换参数
        //swr_ctx = swr_alloc_set_opts(NULL,  // we're allocating a new context
                        //AV_CH_LAYOUT_MONO,  // out_ch_layout
                        //AV_SAMPLE_FMT_S16,    // out_sample_fmt
                        //16000,                // out_sample_rate
                        //AV_CH_LAYOUT_MONO, // in_ch_layout
                        //AV_SAMPLE_FMT_FLTP,   // in_sample_fmt
                        //frame->sample_rate,                // in_sample_rate
                        //0,                    // log_offset
                        //NULL);                // log_ctx
        ////swr_ctx = swr_alloc_set_opts(NULL, dst_layout, dst_format, dst_sample_rate,
                ////frame->channel_layout, (AVSampleFormat)frame->format, frame->sample_rate, 0, 0);
        //if (!swr_ctx || swr_init(swr_ctx) < 0)
            //return ;
    if(NULL==swr_ctx)
    {
        out_ch_layout = av_get_default_channel_layout(1);
        out_format = AV_SAMPLE_FMT_S16;
        out_sample_rate = 16000;

        swr_ctx = swr_alloc();
        swr_alloc_set_opts(swr_ctx, out_ch_layout, out_format, out_sample_rate,
                dec_ctx->channel_layout, dec_ctx->sample_fmt, dec_ctx->sample_rate, 0,
                NULL);
        int ret = swr_init(swr_ctx);
        printf("swr_init = %d\n", ret);
        if(ret<0) exit(0);
    }
    if(NULL==out_buffer)
    {
        out_buffer = (uint8_t *) av_malloc(44100 * 2);
    }

        // 计算转换后的sample个数 a * b / c
        int dst_nb_samples = av_rescale_rnd(swr_get_delay(swr_ctx, frame->sample_rate) + frame->nb_samples, frame->sample_rate, out_sample_rate, AVRounding(1));
        //printf("frame->nb_samples : %d\n", frame->nb_samples);
        //printf("dst_nb_samples : %d\n", dst_nb_samples);
        // 转换，返回值为转换后的sample个数
        int out_nb_samples = swr_convert(swr_ctx, &out_buffer, dst_nb_samples, (const uint8_t **) frame->data, frame->nb_samples);
        //printf("out_nb_samples : %d\n", out_nb_samples);
        int out_channals_nb = av_get_channel_layout_nb_channels(out_ch_layout);
        //int size = out_nb_samples * out_channals_nb * av_get_bytes_per_sample(dst_format);
        int size = av_samples_get_buffer_size(NULL, out_channals_nb, out_nb_samples, out_format, 1);
        printf("out_size : %d\n", size);

        if(0==outdec)
        {
            outdec = fopen("outdec.pcm", "wb");
        }
        if(0!=outdec)
        {
            fwrite(out_buffer, 1, size, outdec);
        }
}

int main(int argc, char* argv[])
{
    //if(argc<2)
    //{
        //printf("usage:dec_mp3 infile\n");
        //return -1;
    //}
    //输入进行解码的mp3文件
    char intput_file[256] = "test.mp3";

    //输出解码后获取到的pcm音频数据文件
    char output_file[256] = "out.pcm";

    if(argc>1)
    {
        strcpy(intput_file, argv[1]);
    }
    if(argc>2)
    {
        strcpy(output_file, argv[2]);
    }


    const char *outfilename, *filename;
    const AVCodec *codec;
    AVCodecContext *c= NULL;
    AVCodecParserContext *parser = NULL;
    int len, ret;
    FILE *f, *outfile;
    uint8_t inbuf[AUDIO_INBUF_SIZE + AV_INPUT_BUFFER_PADDING_SIZE];
    uint8_t *data;
    size_t   data_size;
    AVPacket *pkt;
    AVFrame *decoded_frame = NULL;

    av_register_all();


    filename    = intput_file;
    outfilename = output_file;

    pkt = av_packet_alloc();

    /* 查找mp3解码器 */
    codec = avcodec_find_decoder(AV_CODEC_ID_MP3);
    if (!codec) {
        fprintf(stderr, "Codec not found\n");
        exit(1);
    }

    parser = av_parser_init(codec->id);
    if (!parser) {
        fprintf(stderr, "Parser not found\n");
        exit(1);
    }

    c = avcodec_alloc_context3(codec);
    if (!c) {
        fprintf(stderr, "Could not allocate audio codec context\n");
        exit(1);
    }

    /* 打开解码器*/
    if (avcodec_open2(c, codec, NULL) < 0) {
        fprintf(stderr, "Could not open codec\n");
        exit(1);
    }

    f = fopen(filename, "rb");
    if (!f) {
        fprintf(stderr, "Could not open %s\n", filename);
        exit(1);
    }
    printf("open intput_file %s ok\n", filename);
    outfile = fopen(outfilename, "wb");
    if (!outfile) {
        av_free(c);
        exit(1);
    }
    printf("open output_file %s ok\n", outfilename);

    /* 解码数据 */
    data      = inbuf;
    data_size = fread(inbuf, 1, AUDIO_INBUF_SIZE, f);

    if (!decoded_frame) {
        if (!(decoded_frame = av_frame_alloc())) {
            fprintf(stderr, "Could not allocate audio frame\n");
            exit(1);
        }
    }
    while (data_size > 0) {
        ret = av_parser_parse2(parser, c, &pkt->data, &pkt->size,
                data, data_size,
                AV_NOPTS_VALUE, AV_NOPTS_VALUE, 0);
        if (ret < 0) {
            fprintf(stderr, "Error while parsing\n");
            exit(1);
        }
        data      += ret;
        data_size -= ret;

        if (pkt->size)
            decode(c, pkt, decoded_frame, outfile);

        if (data_size < AUDIO_REFILL_THRESH) {
            memmove(inbuf, data, data_size);
            data = inbuf;
            len = fread(data + data_size, 1,
                    AUDIO_INBUF_SIZE - data_size, f);
            if (len > 0)
                data_size += len;
        }
    }

    /* 处理最后的数据 */
    pkt->data = NULL;
    pkt->size = 0;
    decode(c, pkt, decoded_frame, outfile);

    fclose(outfile);
    fclose(f);

    avcodec_free_context(&c);
    av_parser_close(parser);
    av_frame_free(&decoded_frame);
    av_packet_free(&pkt);

    return 0;
}


